/* eslint-disable multiline-ternary */
/* eslint-disable implicit-arrow-linebreak */
// Third Party Libarary
import { useSkin } from '@hooks/useSkin'
import { Icon } from '@iconify/react'
import classNames from 'classnames'
import { useFormik } from 'formik'
import PaymentElementsWrapper from './PaymentElementsWrapper'
import { X } from 'react-feather'
import { useDispatch, useSelector } from 'react-redux'
import {
  Badge,
  Button,
  Col,
  Form,
  Modal,
  ModalBody,
  ModalFooter,
  ModalHeader,
  Row,
  Spinner
} from 'reactstrap'
import * as Yup from 'yup'
import amex from '../../assets/images/amex.png'
// Components
import { useState } from 'react'
import { getAllBillingAction } from '../../redux/billing/billingAction'
import { payClientInvoiceStripeCardAction } from '../../redux/stripe/stripeAction'
import { isObjEmpty } from '../../utility/Utils'
import useScrollBar from '../../utility/hooks/useScrollBar'
import FormGroupElement from '../formGroup/FormGroupElement'
import PaymentModalBox from './PaymentModalBox'

const ModalBox = ({ basicModal, setBasicModal, data, offset, limit }) => {
  useScrollBar({ open: basicModal })
  const { skin } = useSkin()
  const [openModal, setOpenModal] = useState(false)
  const invoiceId = data?.id
  const dispatch = useDispatch()

  // store
  const { getAllCards, getAllCardsLoading, payStripeCardLoading } = useSelector(
    (state) => state.stripe
  )
  const rows = getAllCards?.sources

  // formik
  const StripePaymentSchema = Yup.object().shape({
    default_payment: Yup.boolean()
  })
  const formik = useFormik({
    initialValues: {
      default_payment: false,
      default_card: rows?.filter(
        (item) => item?.id === getAllCards?.default_source
      )[0]?.id
    },
    enableReinitialize: true,
    validationSchema: StripePaymentSchema,
    onSubmit: async (values, { resetForm }) => {
      if (isObjEmpty(formik.errors)) {
        const data = {
          card_id: values.default_card
        }
        dispatch(
          payClientInvoiceStripeCardAction({
            id: invoiceId,
            data,
            callback: () => {
              resetForm()
              setBasicModal(false)
              dispatch(getAllBillingAction({ offset, limit }))
            }
          })
        )
      }
    }
  })

  const cancel = <X className="pointer" onClick={() => setBasicModal(false)} />
  return (
    <div>
      <Modal
        isOpen={basicModal}
        toggle={() => setBasicModal(!basicModal)}
        className="ModalDialoge  modal-paynow"
      >
        {/* <PaymentElement/> */}
        <ModalHeader className="mt-2 ModalHeader pb-0 d-flex align-items-center ">
          <span className="mb-0 fw-bold fs-22">Payment Information</span>
          {cancel}
        </ModalHeader>
        <Form onSubmit={formik.handleSubmit}>
          <ModalBody className="modalBody pt-0">
            <Row className="sm-column-reverse">
              <Col lg={8} md={8} className="padding-right-0 sm-borders">
                {getAllCardsLoading ? (
                  <div className="d-flex justify-content-center">
                    <Spinner size="lg" color="blue" />
                  </div>
                ) : rows?.length > 0 ? (
                  rows?.map((item, i) => {
                    const cardFormat =
                      item?.card?.brand === 'amex'
                        ? `XXXX XXXXXX X${item?.card?.last4}`
                        : `XXXX XXXX XXXX ${item?.card?.last4}`
                    return (
                      <div className="d-flex-sm" key={i}>
                        <div
                          className="saved_card_elements border mb-1 pointer"
                          onClick={() =>
                            formik.setFieldValue('default_card', item.id)
                          }
                        >
                          <div className="saved_card_elements--card pointer">
                            <div className="sm-d-flex">
                              <FormGroupElement
                                type="radio"
                                inputName={item.id}
                                labelClassName="fs-s-med "
                                checked={formik.values.default_card === item.id}
                                onChange={() =>
                                  formik.setFieldValue('default_card', item.id)
                                }
                                inputClassName={classNames({
                                  lightColors: skin === 'dark'
                                })}
                                formGroupClassName="client_profile--checkbox saved_card_elements--radio"
                              />
                              {item?.card?.brand === 'visa' ? (
                                <Icon icon="logos:visa" width={35} />
                              ) : item?.card?.brand === 'mastercard' ? (
                                <Icon icon="logos:mastercard" width={33} />
                              ) : item?.card?.brand === 'amex' ? (
                                <img
                                  src={amex}
                                  alt={item?.card?.brand}
                                  width={33}
                                  className="amex-card"
                                />
                              ) : (
                                <Icon
                                  icon="fluent:payment-20-filled"
                                  width={33}
                                />
                              )}
                            </div>
                            <div>
                              <FormGroupElement
                                type="text"
                                inputName="cardNumber"
                                value={cardFormat}
                                disabled
                                inputClassName={classNames({
                                  lightColors: skin === 'dark'
                                })}
                                formGroupClassName="saved_card_elements--cardNumber pointer"
                              />
                            </div>
                          </div>
                          <div className="saved_card_elements--sm-default-box pointer">
                            {formik.values.default_card === item.id && (
                              <Badge className="saved_card_elements--default-badge">
                                Default Card
                              </Badge>
                            )}
                          </div>
                          <div className="saved_card_elements--cardExpiry">
                            <FormGroupElement
                              type="text"
                              inputName="cardexpiry"
                              value={`${item?.card?.exp_month}/${
                                item?.card?.exp_year % 100
                              }`}
                              disabled
                              inputClassName={classNames({
                                lightColors: skin === 'dark'
                              })}
                              formGroupClassName="saved_card_elements--cardNumber"
                            />
                          </div>
                        </div>
                      </div>
                    )
                  })
                ) : (
                  <>
                    <Button
                      size="sm"
                      className=" button-green"
                      onClick={() => {
                        setOpenModal(!openModal)
                      }}
                    >
                      <span>Payment Method</span>
                    </Button>
                    <div className="text-center py-1">No Cards</div>
                  </>
                )}
              </Col>
              <Col>
                <div className="ChargeDetails ">
                  <p className="mb-0 fs-s-med">Charge:</p>
                  <span className="fw-bold fs-l-med black">$ {data?.fees}</span>

                  <p className="mt-1 mb-0 fs-s-med sm-setup-invoice">
                    Invoice Number:
                  </p>
                  <span className="fw-bold fs-l-med black ">
                    #{data?.invoice_number}
                  </span>
                </div>
              </Col>
            </Row>
          </ModalBody>
          <ModalFooter className="ModalFooter ModalFooter-pay">
            <Button
              size="sm"
              type="button"
              className="ModalCancel"
              onClick={() => setBasicModal(!basicModal)}
            >
              Cancel
            </Button>
            <Button
              size="sm"
              type="submit"
              className="ModalAdd"
              disabled={payStripeCardLoading}
            >
              {payStripeCardLoading && (
                <Spinner size="sm" className="spinner-size-paynow" />
              )}
              <span className="mx-1">Pay Now</span>
            </Button>
          </ModalFooter>
        </Form>
      </Modal>
      <PaymentElementsWrapper basicModal={openModal} setBasicModal={setOpenModal} />
    </div>
  )
}

export default ModalBox
